<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // function fn({id, uname}) {
    //   id = id || '789'
    //   console.log(id)
    //   console.log(8888888, uname)
    // }

    // fn({
    //   uname: 'qwer'
    // })


    function handleData(data) {
      let str = ''
      for(let key in data) {
        str += `${key}=${data[key]}&`
      }
      return str.slice(0, str.length - 1)
    }

    // es6 默认参数
    function itheima({type = '123123312', url, data, success}) {
      // type = type || 'GET'

      let str = handleData(data)
      let xhr = new XMLHttpRequest()
      console.log(77777777, type)

      if(type.toUpperCase() === 'GET') {
        xhr.open('GET', `${url}?${str}` )
        xhr.send()
      } else {
        xhr.open('POST', url )
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(str)
      }

      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200) {
          success( JSON.parse(xhr.responseText) )
        }
      }
    }

    itheima({
      type: 'GET',
      url: 'http://www.liulongbin.top:3006/api/getbooks',
      data: {
        // bookname: '张三你真好',
        // author: '张三',
        // publisher: '张三的书'
      },
      success: function(res) {
        console.log(888, res)
      }
    })
  </script>
</body>
</html>